<?php

namespace app\admin\controller;


use think\facade\Env;

class Cate extends Base
{
    //栏目列表
    public function catelist()
    {
        $cates = model('Category')->order('sort')->paginate(10);
        $this->assign('cates', $cates);
        return view();
    }

    // 栏目添加
    public function cateadd()
    {
        if (request()->isAjax()) {
            $data = [
                'catename' => input('post.catename'),
                'sort' => input('post.sort'),
            ];
            $result = model('Category')->add($data);
            if ($result == 1) {
                $this->success('栏目添加成功', 'admin/cate/catelist');
            } else {
                $this->error($result);
            }
        }

        return view();
    }


    // 编辑栏目
    public function cateedit()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('post.id'),
                'catename' => input('post.catename'),
                'sort' => input('post.sort')
            ];
            $result = model('Category')->edit($data);
            if ($result == 1) {
                $this->success('栏目编辑成功', 'admin/cate/catelist');
            } else {
                $this->error($result);
            }

        }


        // get访问
        $cate_info = model('Category')->where('id', input('id'))->find();
        if (!$cate_info) {
            // 抛出404异常
            abort(404, '页面未找到');
        }
        $this->assign('cate_info', $cate_info);
        return view();
    }


    // 删除栏目
    public function catedel()
    {
        if (request()->isAjax()){
            $cate_info = model('Category')
                ->with('article,article.comments')
                ->find(input('id'));
            if (!$cate_info) {
                // 抛出404异常
                abort(404, '该栏目未找到');
            }
            foreach ($cate_info['article'] as $k => $v){
                // 循环删除栏目下的文章及其关联的评论
                $v->together('comments')->delete();
            }
            // 最后再删除该栏目
            $result = $cate_info->delete();
            if ($result > 0){
                $this->success('栏目删除成功', 'admin/cate/catelist');
            }else{
                $this->error('栏目删除失败');
            }
        }

    }
}
